<template>
  <div>
    <Row>
      <i-col span="24" class="operation_item y_query_right" style="">
        <Select placeholder="排序方式" v-model="sort" class="y_condition" clearable style="text-align: left;width: 120px;">
          <Option value="create_time desc">时间降序</Option>
          <Option value="create_time asc">时间升序</Option>
          <Option value="spam_score desc">评分降序</Option>
          <Option value="spam_score asc" >评分升序</Option>
        </Select>
        <Input v-model.trim="tParam.subject" placeholder="标题关键词" clearable class="y_condition"></Input>
        <Input v-model.trim="tParam.emailTo" placeholder="收件人邮箱" style="min-width: 170px;" clearable class="y_condition"></Input>
        <Input v-model.trim="tParam.userNo" placeholder="用户编号或发件人邮箱" style="min-width: 170px;" clearable class="y_condition"></Input>
        <Select placeholder="标签" v-model="tParam.tags" class="y_condition" style="text-align: left;"
                clearable filterable allow-create @on-clear="tParam.tag=null" @on-create="createSearchTag">
          <Option v-for="tag in tagList" :value="tag">{{ tag }}</Option>
        </Select>

        <DatePicker placeholder="开始时间" type="datetime" v-model="tParam.startTime" format="yyyy-MM-dd HH:mm"
                    style="min-width: 150px" class="y_condition"></DatePicker>
        -
        <DatePicker placeholder="截止时间" type="datetime" v-model="tParam.endTime" format="yyyy-MM-dd HH:mm"
                    class="y_condition"></DatePicker>
        <Button type="primary" icon="md-search" @click="search()" class="y_condition">查询</Button>

      </i-col>
    </Row>

    <Row justify="end" >
      <i-col style="margin-bottom: -0.1rem;">
        <Checkbox v-model="tParam.isAssign" class="y_condition" style="min-width: 180px" >只查询未分配邮件</Checkbox>
<!--        <Checkbox v-model="tParam.isAll" class="y_condition" style="min-width: 250px" v-has=tRole.EMAIL_1_103>查询全部（包含未分配给我的）</Checkbox>-->
        <Button type="error" icon="ios-trash-outline" class="y_condition" @click="deleteAction()"
                v-has=tRole.EMAIL_1_101 :disabled="messageSelected.length==0">删除</Button>
        <Button type="primary" icon="ios-contact-outline" class="y_condition" @click="showAssign()"
                v-has=tRole.EMAIL_1_102 :disabled="messageSelected.length==0">批量指派</Button>

      </i-col>
    </Row>
    <List>
      <ListItem style="display: flex;flex-direction: column;align-items: flex-start;margin-left: 1rem;">
        <Checkbox v-model="isCheckedAllMessage" @on-change="handleCheckAll">全选</Checkbox>
      </ListItem>
      <CheckboxGroup v-model="messageSelected" @on-change="checkChange">
      <list-item class="list_item" v-for="(item,index) in emailData">
        <div style="width:100%;padding: 0 0.5rem;"  >
            <Row style="cursor: pointer;text-align: left" type="flex" justify="space-between" align="top">
              <i-col order="1" xs="12" sm="2">
                <Checkbox :label="item" :value="index">{{ check }}</Checkbox>
              </i-col>
              <i-col order="2" xs="24" sm="20" flex="auto" @click.native="showEmail(index)">
                <span style="font-weight: 500;font-size: 0.8rem">{{ item.subject }}</span>
              </i-col>
              <i-col order="3" xs="12" sm="2">
                <Tag @click.stop type="border" color="red" style="margin-left: 0.1rem;">评分：{{ item.spamScore}}</Tag>
              </i-col>
            </Row>
            <Row @click.native="showEmail(index)" style="cursor: pointer;text-align: left" type="flex" justify="space-between" align="top">
              <i-col xs="24" sm="24" >
                <p  v-if="item.text!=null" class="base_key" style="margin-left: 1.5rem">{{ item.text.substring(0, 80) }}</p>
              </i-col>
            </Row>
          <Row justify="end" @click.native="showEmail(index)" style="margin-top: 0.5rem;padding: 0.25rem 0">
            <i-col>
              <span v-if="item.tags!=null && item.tags.length>0" v-for="(tag, index) in parseTags(item.tags)">
                <Tag @click.stop  :color="getTagColor(index)">
                  {{tag}}
                </Tag>
              </span>

              <span v-if="item.encodeName!=null" @click.stop style="min-width: 10rem;">
                <span class="list_value">用户：<span style="font-weight: bold;color: #2db7f5">{{item.encodeName}}</span></span>
              </span>


              <KeyValueView title="负责人">
                {{item.employeeId!==null?item.employeeName:'无'}}
                <span style="color:#2d8cf0;cursor: pointer;margin-left: 0.25rem" v-has=tRole.EMAIL_1_201 @click.stop="showAssign(item.emailAddressId)">
                    {{item.employeeId!==null?'更改':'分配'}}
                </span>
              </KeyValueView>


              <span @click.stop class="minWidth">
                状态：
                <span class="list_value" style="font-weight: bold;padding-right: 0.2rem" v-text="emailStatusLabel(item.emailStatus,item.employeeId)"></span>
                <span style="color:#2D8cF0;font-size: 13px;cursor: pointer" v-has=tRole.EMAIL_1_202
                      @click="showStateModal(item.id, item.emailStatus)">
                  <span>更改</span>
                </span>
              </span>

            </i-col>

          </Row>
          <Row justify="end" align="middle">
            <i-col flex="auto" style="text-align: right">
              <KeyValueView title="发件邮箱">{{item.virtualName}}</KeyValueView>
              <KeyValueView title="收件邮箱">{{item.emailTo}}</KeyValueView>
              <KeyValueView title="时间">{{ $tiyBJTime(new Date(item.createTime).getTime()) }}</KeyValueView>
            </i-col>

          </Row>
        </div>
      </list-item>
      </CheckboxGroup>
    </List>

    <div style="float: right;margin-top: 1rem">
      <Page :total="page.total" :page-size="page.stepNumber" :current="page.currentPage" @on-change="changePage"
            @on-page-size-change="sizeChange" :page-size-opts="[20,40,60,100]"
            show-sizer show-elevator/>
    </div>

    <!--删除确认弹出框-->
    <Modal
      v-model="status.modalDelete.isShow"
      title="确认删除"
      :loading="status.modalDelete.isLoading"
      @on-ok="deleteAll">
      <p>确认删除邮件?</p>
    </Modal>

    <!-- 邮件详情 -->
    <Modal
      v-model="status.showEmail.isShowing"
      title="邮件详情"
      :mask-closable="false"
      :styles="{top: '20px',bottom:'20px',width:'65%'}">
      <AEmailDetail :sys-email="0" :email-to="tParam.email.emailTo" :virtual-name="tParam.email.virtualName"
                    :create-time="tParam.email.createTime" :encode-name="tParam.email.encodeName"
                    :subject="tParam.email.subject" :content="tParam.email.content" :type="2" :email-address-id="tParam.email.emailAddressId"
                    :attachment="tParam.email.attachment" :id="tParam.email.id" :selected-tags="tParam.email.tags"
                    :attachment-count="tParam.email.attachmentCount" :attachment-show="tParam.email.attachmentShow"
                    @reply="reply" @spam="spam" @addBlacklist="addBlacklist" ref="AEmailDetail"></AEmailDetail>
      <div slot="footer"></div>
    </Modal>

    <!-- 回复邮件 -->
    <Modal
      v-model="status.replayEmail.isShowing"
      title=""
      :mask-closable="false"
      :styles="{top: '20px',bottom:'20px',width:'80%'}">
      <send-email v-bind:receiveUser="tParam.email.selectedUsers" :is-send="false"s v-bind:isRefresh="false"
                       v-on:listenSendEmailEvent="sendSuccess" ref="SendEmail"></send-email>
      <div slot="footer"></div>
    </Modal>

    <!-- 分配负责人 -->
    <Modal v-model="status.modalAssignUser.isShow" title="选择负责人"
           :styles="{top: '20px',bottom:'20px',width:'40%',}" :scrollable=false @on-ok="assignToEmployee()" >
      <Row >
        <i-col span="4">&nbsp;</i-col>
        <i-col span="16">
          <SearchCustomerService ref="employeeSearch" @choose-customer-service="chooseCustomerService"></SearchCustomerService>
        </i-col>
        <i-col span="4">&nbsp;</i-col>
      </Row>
    </Modal>

    <!-- 邮件状态 -->
    <Modal v-model="status.modalStatusChange.isShow" draggable title="邮件状态"
           @on-ok="complete"  :width="this.$yMobile()?'80%':'500'">
      <Select v-model="tParam.emailStatus"  >
        <Option v-for="item in emailStatusDict" :value="item.value" :key="item.value">{{ item.label }}</Option>
      </Select>
    </Modal>

  </div>
</template>

<!--javascript 代码-->
<script>
import tiyData from "./js/parseEmail/parse_data";
import AEmailDetail from "../email/EmailDetail.vue"
import SendEmail from "../email/SendEmailTemplate.vue"
import TrashEmail from "./TrashEmail";
import {isEmpty} from "../js/commonUtils";
import KeyValueView from "../widgets/KeyValueView";
import SearchCustomerService from "../widgets/SearchCustomerService";

import {
  init,
  emailList,
  deleted,
  webDelete,
  showEmail,
  replyEmail,
  spam,
  addBlacklist,
  webDeleteAll,
} from "./js/parseEmail/parse_fun";



export default {
  data() {
    return {
      tRole:{
        EMAIL_1_101:"EMAIL-1-101",
        EMAIL_1_102:"EMAIL-1-102",
        EMAIL_1_103:"EMAIL-1-103",
        EMAIL_1_201:"EMAIL-1-201",
        EMAIL_1_202:"EMAIL-1-202",
        COMMON_1_100:"COMMON-1-100",
      },
      page: tiyData.tPage,
      tParam: tiyData.tParam,
      emailData: tiyData.tData.emailList,
      status: tiyData.tStatus,
      tagList: tiyData.tData.tagList,
      index2: 0,
      check: '',
      isCheckedAllMessage: false,
      messageSelected: [],
      sort:'create_time desc',
      emailStatusDict:[
        {  value: 100,label: '未回复'},
        {  value: 300,label: '已回复'},
      ],
      tagColor: [
          "red","green","blue","navy","maroon","purple","yellow"
      ]
    }
  },
  components: {KeyValueView, AEmailDetail, SendEmail,TrashEmail,SearchCustomerService},
  props:{
    sysEmail:Number,
  },
  created(){
    init(this,tiyData);
  },
  methods: {
    init(){
      init(this,tiyData);
    },
    search() {
      emailList(this, tiyData);
    },
    changePage(page) {
      tiyData.tPage.currentPage = page;
      emailList(this, tiyData);
    },
    sizeChange(page) {
      tiyData.tPage.stepNumber = page;
      emailList(this, tiyData);
    },
    showEmail(index) {
      if(this.$authority("EMAIL-1-203")){ //有权限才能查看邮件详情
        this.index2 = index;
        showEmail(this, tiyData, index)
      }
    },
    reply() {
      replyEmail(this, tiyData, this.index2);
    },
    spam(){
      spam(this, tiyData, this.index2);
    },
    addBlacklist(){
      addBlacklist(this, tiyData, this.index2);
    },
    sendSuccess(isSuccess) {
      if (isSuccess) {
        tiyData.tStatus.replayEmail.isShowing = false;
        //修改邮件状态为已回复
        let emailInfo=tiyData.tData.emailList[this.index2];
        tiyData.tParam.id=emailInfo.id;
        tiyData.tParam.emailStatus=300;
        this.complete();
      }
    },
    deleteAction() {
      deleted(this, tiyData);
    },
    deleteItem() {
      webDelete(this, tiyData);
    },
    deleteAll() {
      webDeleteAll(this, tiyData);
    },
    createSearchTag(query) {
      if (this.tagList.find(function (tag) {
        return query == tag;
      }) == null) {
        this.tagList.push(query);
      }
    },
    parseTags(tags) {
      return this.$toJson(tags);
    },
    checkChange() {
      if (this.messageSelected.length == this.emailData.length) {
        this.isCheckedAllMessage = true;
      } else {
        this.isCheckedAllMessage = false;
      }
    },
    handleCheckAll() {
      let self = this;
      if (this.isCheckedAllMessage) {
        this.messageSelected.splice(0, this.messageSelected.length);
        for(let i=0;i<this.emailData.length;i++){
          self.messageSelected.push(this.emailData[i]);
        }
      } else {
        this.messageSelected.splice(0, this.messageSelected.length);
      }
    },
    showAssign(emailAddressId){ //显示分配用户窗口
      //单条分配
      if(emailAddressId){
        tiyData.tStatus.modalAssignUser.isShow = true;
        tiyData.tParam.emailStatusParam.employeeId='';
        tiyData.tParam.emailStatusParam.employeeName='';
        tiyData.tParam.emailStatusParam.emailAddressId = emailAddressId;
      }else{
        if(this.messageSelected.length==0){
          this.$Message.error("请勾选要分配的用户！");
          return;
        }
        tiyData.tStatus.modalAssignUser.isShow = true;
        tiyData.tParam.emailStatusParam.emailAddressId='';
      }
      this.$refs['employeeSearch'].clearSelectedEmployee();
    },
    chooseCustomerService(value){
      if(value!=null){
        tiyData.tParam.emailStatusParam.employeeId = value.employeeId;
        tiyData.tParam.emailStatusParam.employeeName = value.userName;
      }
    },
    assignToEmployee(){ //分配用户给指定员工
      let self = this;
      if(!tiyData.tParam.emailStatusParam.employeeId){
        this.$Message.error("请选择负责人！");
        return;
      }
      //
      self.$Spin.show();
      if(tiyData.tParam.emailStatusParam.emailAddressId!=''){
        self.$apiEmail.updateEmailAddress({
          "employeeId":tiyData.tParam.emailStatusParam.employeeId,
          "type":2,
          "id":tiyData.tParam.emailStatusParam.emailAddressId,
        }).then(function (response) {
          self.$Spin.hide();
          if (response.success) {
            self.search();
          } else {
            self.$Message.error(response.errorMessage);
          }
        });

      }else{
        let ids=[];
        self.messageSelected.forEach(email=>{
          ids.push(email.emailAddressId);
        });

        self.$apiEmail.updateContactEmailLAddressBatch({
          "employeeId":tiyData.tParam.emailStatusParam.employeeId,
          "employeeName":tiyData.tParam.emailStatusParam.employeeName,
          "ids":[...new Set(ids)],
        }).then(function (response) {
          self.$Spin.hide();
          if (response.success) {
            self.search();
          } else {
            self.$Message.error(response.errorMessage);
          }
          self.messageSelected.splice(0,self.messageSelected.length);
        });

      }

    },
    complete(){
      let self = this;
      self.$Spin.show();
      self.$apiEmail.updateEmailProcess({
        "id": tiyData.tParam.id,
        "emailStatus":tiyData.tParam.emailStatus,
      }).then(function (response) {
        self.$Spin.hide();
        if (response.success) {
          self.search();
        } else {
          self.$Message.error(response.errorMessage);
        }
      });
    },
    emailStatusLabel(emailStatus,employeeId){
      if(emailStatus==null){
        return '';
      }
      if(emailStatus==300){
        return "已回复";
      }else{
        return isEmpty(employeeId)?"待分配":"已分配";
      }
    },
    showStateModal(id, emailStatus){ //修改状态窗口
      tiyData.tParam.id = id;
      tiyData.tParam.emailStatus = emailStatus;
      tiyData.tStatus.modalStatusChange.isShow = true;
    },
    getTagColor(index) {
      let len = this.tagColor.length;
      return this.tagColor[index%len];
    }
  }
}
</script>

<!--css样式-->
<style lang="less" scoped>
@import  (once,optional)  "../css/base";

.table_css {
  margin-top: 20px;
  margin-bottom: 20px;
}

.operation_item {
  text-align: left;
  margin-right: 20px;
}

.list_value {
  font-size: 13px;
  color: @tiyTextDescColor;
  padding-right: 1rem;
  word-wrap: break-word;
  word-break: break-all;
  overflow: hidden;
}

.list_item {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.list_item:hover {
  background: @tiySectionColor;
}

.list_key{
  font-size: 15px;
  color: @tiyTextLightColor;
  padding: 0rem 0.3rem;
}

.list_value{
  font-size: 13px;
  color: @tiyTextDescColor;
  padding-right: 1rem;
  word-wrap:break-word;
  word-break:break-all;
  overflow: hidden;
}

.minWidth{
  min-width: 5rem;
  margin-right: 1rem;
}

</style>
